package com.mty.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.mty.common.entity.AclRole;
import com.mty.common.entity.AclRoleUser;
import com.mty.common.vo.Result;
import com.mty.system.dao.AclRoleDao;
import com.mty.system.dao.AclUserRoleDao;
import com.mty.system.service.AclRoleService;
import com.mty.system.vo.FenRoleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author ：Teacher马（2508531326@qq.com）
 * @date ：Created in 2022/12/6 10:08
 * @description：
 * @modified By：
 * @version:
 */
@Service
public class AclRoleServiceImpl implements AclRoleService {
    @Autowired
    private AclRoleDao aclRoleDao;
    @Autowired
    private AclUserRoleDao aclUserRoleDao;
    @Override
    public Result findRoleByUserId(Long userid) {
        //1. 查询所有的角色
        List<AclRole> aclRoles = aclRoleDao.selectList(null);
        //2. 查询当前用户具有的角色
        List<AclRole> userRoles = aclRoleDao.selectByUserId(userid);
       /* List<String> userRoleIds = userRoles.stream().map(item -> item.getId()).collect(Collectors.toList());*/
        Map<String,Object> map=new HashMap<>();
        map.put("aclRoles",aclRoles);
        map.put("userRoles",userRoles);
        return new Result(2000,"查询成功",map);
    }

    @Override
    @Transactional
    public Result fenUserRole(FenRoleVo fenRoleVo) {

        //删除当前用户具的角色
        UpdateWrapper<AclRoleUser> wrapper=new UpdateWrapper<>();
        wrapper.eq("user_id",fenRoleVo.getUserId());
        aclUserRoleDao.delete(wrapper);
        //添加该用户具有的新角色 insert into 表名 values(值,值...)(值,值...)(值,值....)  动态sql语句
        List<AclRoleUser> list=new ArrayList<>();
        for(String roleId:fenRoleVo.getRoleIds()){
            AclRoleUser aclRoleUser=new AclRoleUser();
            aclRoleUser.setIsDeleted(0);
            aclRoleUser.setRoleId(roleId);
            aclRoleUser.setUserId(fenRoleVo.getUserId());
            aclRoleUser.setGmtCreate(LocalDateTime.now());
            aclRoleUser.setGmtModified(LocalDateTime.now());
            list.add(aclRoleUser);
        }
        aclUserRoleDao.batchInsert(list);

        return new Result(2000,"分配角色成功");
    }
}
